package javaer.starter.util;

import javaer.starter.constant.SourceDirectoryEnum;
import javaer.starter.constant.StorePathEnum;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

/**
 * @author yangzhen
 * @date 2023/6/14 11:04
 * @since 1.0.0
 */
public class FileUtil {
    private static Logger logger = LoggerFactory.getLogger(FileUtil.class);

    public static Path createIfNotExistsDirectory(String directory) throws IOException {
        Path path = Paths.get(directory);
        if (!Files.exists(path)) {
            Files.createDirectories(path);
        }
        return path;
    }


    public static void deleteProject(Path path) {
        if (!(path.toString().startsWith(StorePathEnum.PROJECT_PATH.getDirectory()) || path.toString().startsWith(StorePathEnum.TEMPLATE_PATH.getDirectory()))) {
            return;
        }
        deleteDir(path.toFile());
        logger.info("删除目录完成： path={}", path.toString());
    }

    private static void deleteDir(File file) {
        if (!file.exists()) {
            return;
        }

        if (file.isDirectory()) {
            File[] files = file.listFiles();
            for (File subFile : files) {
                deleteDir(subFile);
            }
        }
        file.delete();
    }

    public static void createDirsIfNotExists(Path path) throws IOException {
        if (!Files.exists(path)) {
            Files.createDirectories(path);
        }
    }

    public static void createFileIfNotExists(Path path, String filename) throws IOException {
        createDirsIfNotExists(path);
        Path resolve = path.resolve(filename);
        if (Files.exists(resolve)) {
            Files.delete(resolve);
        }
        Files.createFile(resolve);
    }

    public static String getDir(Path basePath, String prefix, String module) {
        String type = basePath.toString().endsWith(SourceDirectoryEnum.SRC_MAIN_RESOURCES.getValue()) ? "resource" : "code";
        return prefix + File.separator + module + File.separator + type + File.separator;
    }
}
